import angular from 'angular';

export default angular.module('app.services', [])

    .service('SystemService', function ($q, $http, hostip) {
        this.getHostIP = function () {
            return hostip;
        }
        let user = {};
        let uid = null;

        return {

            getUser: function () {
                let userCache = null;

                if (!sessionStorage.user) {
                    userCache = null;
                }
                else {
                    userCache = JSON.parse(sessionStorage.user);
                }

                //判断是否存在用户缓存
                if (user && userCache) {
                    //判断本地缓存和session或者localstorage里面的用户信息是否相同
                    if (user._id !== userCache._id) {
                        user = userCache;
                    }
                } else if (!user && userCache) {
                    user = userCache;
                }
                return user;
            },
            setUser: function (newUser) {
                user = newUser;
                sessionStorage.user = angular.toJson(newUser);
            },//网页保持原来用户

            getUID: function () {
                if (!user) {//如果它不是空的
                    user = angular.fromJson(localStorage.user);
                    uid = user._id;
                }
                return uid;
            },
            setUID: function (newUID) {
                uid = newUID;
                sessionStorage.uid = newUID;
            },
            getHostIP: function () {
                // return window.location.protocol + '//' + window.location.host;
                return hostip;
            }

        }

    })


    .service('UserService', function ($q, $http, SystemService) {// $q 是内置服务，可以直接使用，其他的是项目里有的
        this.register = function (content) {
            let param = {
                "name": content.name,
                "pwd": content.pwd
            };
            console.log(param);

            var deferred = $q.defer();//生成deferred异步对象
            $http.post(SystemService.getHostIP() + '/users/register', param)//封装好的param传给后台
                .then(
                    function (data, status, headers, config) {
                        deferred.resolve(data);//执行到这里时，改变deferred状态为执行成功，返回data为从后台取到的数据
                    }
                )
                .catch(
                    function (data, status, headers, config) {
                        deferred.reject(data);//执行到这里时，改变deferred状态为执行失败，返回data为报错
                    }
                );
            return deferred.promise;//控制异步运行完成
            //return deferred.promise起到保护作用，不允许函数外部改变函数内的deferred状态

        };
        this.login = function (content) {
            let param = {
                "name": content.inputEmail,
                "pwd": content.inputPassword
            };
            console.log(param);
            return $http.post(SystemService.getHostIP() + '/users/login', param)
        };

        // this.retypedPassword = function (content) {
        //     let param = {
        //         "pwd": content.inputPassword
        //     };
        //     console.log(param);
        //     return SystemService.post('/users/retypedPassword', param);
        // };


        this.saveTimetable = function (content) {
            var deferred = $q.defer();

            // $http.defaults.headers.common['Token'] = SystemService.getLoginToken();

            $http.post(SystemService.getHostIP() + '/timetable/saveAndUpdateTimetable', content)
                .then(
                    function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code == 0) {
                            deferred.resolve(data.returnValue);
                        } else {
                            deferred.reject(data.errorReason);
                        }
                    }
                )
                .catch(
                    function (data) {
                        deferred.reject("出错了,请重试!");
                    });
            return deferred.promise;
        }

        this.getTimetable = function (content) {

            console.log(content)
            var deferred = $q.defer();
            let param = {
                userId: content.userId,
            };
            console.log(param.userId);


            $http.post(SystemService.getHostIP() + '/timetable/getTimetable', param)
                .then(
                    function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code == 0) {
                            console.log(1)
                            deferred.resolve(data.returnValue);//存进promise里；
                        } else {
                            console.log(2)
                            deferred.reject(data.errorReason);
                        }
                    }
                )
                .catch(function (data) {
                    deferred.reject("出错了,请重试!");
                });
            return deferred.promise;

        }
    })



